package com.c.ctgproject.ui.vehicleadmission

import android.app.Activity
import android.app.ProgressDialog
import android.content.Intent
import android.os.Bundle
import android.os.Environment
import android.text.TextUtils
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.c.ctgproject.R
import com.c.ctgproject.customview.GlideImageLoader
import com.c.ctgproject.customview.ImagePickerLoader
import com.c.ctgproject.mode.carEntrance
import com.c.ctgproject.retrofit.Response
import com.c.ctgproject.ui.files.callback.IsDeleteManager
import com.c.ctgproject.utils.*
import com.c.ctgproject.utils.pickerimage.utils.StorageType
import com.c.ctgproject.utils.pickerimage.utils.StorageUtil
import com.c.ctgproject.utils.pickerimage.utils.StringUtil
import com.c.ctgproject.wiget.dialog.LoadingDialog
import com.jaeger.library.StatusBarUtil
import com.lwkandroid.imagepicker.ImagePicker
import com.lwkandroid.imagepicker.data.ImageBean
import com.lwkandroid.imagepicker.data.ImagePickType
import com.lwkandroid.widget.ninegridview.NineGirdImageContainer
import com.lwkandroid.widget.ninegridview.NineGridBean
import com.lwkandroid.widget.ninegridview.NineGridView
import com.nanchen.compresshelper.CompressHelper
import kotlinx.android.synthetic.main.activity_vehicleadmission.*
import kotlinx.android.synthetic.main.title.*
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File


/**
 *
 * 车辆入场 页面 入库前 (待初验车辆列表进入)
 */
@Suppress(
    "DEPRECATED_IDENTITY_EQUALS", "DEPRECATION",
    "NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS"
)
class VehicleAdmissionActivity : AppCompatActivity(), View.OnClickListener, NineGridView.onItemClickListener
//    , View.OnTouchListener
{
    private val ownerPlate by lazy { intent.getStringExtra("ownerPlate") }
    //图片选择返回值
    private val REQUEST_CODE_PICKER = 100
    private val statusColor: StatusColor = StatusColor()
    private var progressDialog: ProgressDialog? = null
    private var vehicleAdmissionViewModel: VehicleAdmissionViewModel? = null
    private var dialogUtils: DialogUtils? = null
    private var drivingLicense = "0"//行驶证 1-有 0-无
    private var registration = "0" //登记证 1-有 0-无
    private var idCardCopy = "0"  //身份证复印件 1-有 0-无
    private var notice = "0" //告知书 1-有 0-无
    private var attorneyPaper = "0" //委托书 1-有 0-无
    private var plateApplicationForm = "0" //机动车申领表 1-有 0-无
    private var carSign = "2"  //车辆标记 1-问题车辆 2-正常车辆
    private var token: String? = null
    private val JPG = ".jpg"
    private val files: ArrayList<File> = ArrayList()
    private var carId: String? = null //车主id
//    private var keyboardUtil: CarKeyboardUtil? = null
    private val loading: LoadingDialog by lazy { LoadingDialog(this) }
    private var operating = "0"//是否营运车辆 1-营运 0-非营运
    //文件上传中标志位
    private var uploadingFlag = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_vehicleadmission)
        StatusBarUtil.setTranslucent(this)
        statusColor.setAndroidNativeLightStatusBar(this, false)
        toolbar_title.text = "车辆入场"
        setSupportActionBar(toolbar)
        supportActionBar?.setHomeButtonEnabled(true)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        supportActionBar?.setDisplayShowTitleEnabled(false)
        event()
        Getdata()
    }

    //车辆入场回调 点击入库按钮回调
    private fun Getdata() {
        vehicleAdmissionViewModel!!.getresponsedata().observe(this, Observer { response: Response<*> ->
            uploadingFlag=false
            MyLog.d("车辆入场回调:$response")
            if (response.status == 0) {
                progressDialog!!.dismiss()
                finish()
                Toast.makeText(applicationContext, response.msg, Toast.LENGTH_SHORT).show()
                IsDeleteManager.isDelete(ownerPlate)
            } else {
                progressDialog!!.dismiss()
                dialogUtils!!.showTwo(this@VehicleAdmissionActivity, "提示", response.msg.handlerNull())
            }
        })


    }

    private fun event() {
        //设置图片加载器，这个是必须的，不然图片无法显示
        ninegridview.setImageLoader(GlideImageLoader())
        //设置显示列数，默认3列
        ninegridview.setColumnCount(3)
        //设置是否为编辑模式，默认为false
        ninegridview.setIsEditMode(true)
        //设置单张图片显示时的尺寸，默认100dp
        ninegridview.setSingleImageSize(150)
        //设置单张图片显示时的宽高比，默认1.0f
        ninegridview.setSingleImageRatio(0.8f)
        //设置最大显示数量，默认9张
        ninegridview.setMaxNum(5)
        //设置图片显示间隔大小，默认3dp
        ninegridview.setSpcaeSize(4)
        //设置删除图片
        //        mNineGridView.setIcDeleteResId(R.drawable.ic_block_black_24dp);
        //设置删除图片与父视图的大小比例，默认0.25f
        //设置删除图片
        //        mNineGridView.setIcDeleteResId(R.drawable.ic_block_black_24dp);
        //设置删除图片与父视图的大小比例，默认0.25f
        ninegridview.setRatioOfDeleteIcon(0.15f)
        //设置“+”号的图片
        ninegridview.setIcAddMoreResId(R.drawable.ic_ngv_add_pic)
        //设置各类点击监听
        ninegridview.setOnItemClickListener(this)
        //隐藏输入框的小键盘
//        etPlateNumber.unShowKeyBoard()
//        keyboardUtil = CarKeyboardUtil(this, etPlateNumber)
        progressDialog = ProgressDialog(
            this@VehicleAdmissionActivity,
            R.style.AppTheme_Dark_Dialog
        )
        progressDialog!!.isIndeterminate = true
        progressDialog!!.setCanceledOnTouchOutside(false)
        progressDialog!!.setCancelable(true)
        carId = intent.getStringExtra("carId")
        token = Utils.getShared2(this, "token")
        dialogUtils = DialogUtils()
        confirm_button1.setOnClickListener(this)
        vehicleAdmissionViewModel = ViewModelProvider(
            this, ViewModelProvider.AndroidViewModelFactory(application)
        ).get(VehicleAdmissionViewModel::class.java)
        //进入页面直接请求的车辆信息
        loading.show()
        vehicleAdmissionViewModel!!.postCarEntrance(token!!, carId!!)
        //进入页面获取的信息
        vehicleAdmissionViewModel!!.getpostcarEntrancedata().observe(this, Observer { response: Response<carEntrance> ->
            loading.dismiss()
            MyLog.d("车辆入场获得的数据:$response")
            if (response.status == 0) {
                ownerPhone.text = setEditText(response.data.ownerPhone.handlerNull())
                carOwner.text = setEditText(response.data.carOwner.handlerNull())
                etPlateNumber.text = setEditText(response.data.ownerPlate.handlerNull())
                carVin.text = setEditText(response.data.carVin.handlerNull())
                CK_1.isChecked = response.data.drivingLicense == "1"
                CK_2.isChecked = response.data.registration == "1"
                CK_3.isChecked = response.data.idCardCopy == "1"
                CK_4.isChecked = response.data.notice == "1"
                CK_5.isChecked = response.data.attorneyPaper == "1"
                CK_6.isChecked = response.data.plateApplicationForm == "1"
                mSellerET.textSet(response.data.salesman.handlerNull())
                //如果为0则为非营运车辆
                if (response.data.isOperatingCar == "1") {
                    mYYTrue.isChecked = true
                    mYYFalse.isChecked = false
                } else {
                    mYYFalse.isChecked = true
                    mYYTrue.isChecked = false
                }

                val flag = response.data.carSign
                flag?.let {
                    when (it) {
                        "2" -> CK_B1.isChecked = true
                        "1" -> CK_B2.isChecked = true
                    }
                }
                remark.setText(response.data.remark)
            } else {
                dialogUtils!!.showTwo(this@VehicleAdmissionActivity, "提示", response.data.handlerNull())
            }

        })

        vehicleAdmissionViewModel!!.error.observe(this, Observer {
            loading.dismiss()
            progressDialog!!.dismiss()
            showToast(it)
        })

        CK_1.setOnCheckedChangeListener { buttonView, isChecked ->
            drivingLicense = if (isChecked) {
                "1"
            } else {
                "0"
            }
        }

        CK_2.setOnCheckedChangeListener { buttonView, isChecked ->
            registration = if (isChecked) {
                "1"
            } else {
                "0"
            }
        }

        CK_3.setOnCheckedChangeListener { buttonView, isChecked ->
            idCardCopy = if (isChecked) {
                "1"
            } else {
                "0"
            }
        }

        CK_4.setOnCheckedChangeListener { buttonView, isChecked ->
            notice = if (isChecked) {
                "1"
            } else {
                "0"
            }
        }

        CK_5.setOnCheckedChangeListener { buttonView, isChecked ->
            attorneyPaper = if (isChecked) {
                "1"
            } else {
                "0"
            }
        }


        CK_6.setOnCheckedChangeListener { buttonView, isChecked ->
            plateApplicationForm = if (isChecked) {
                "1"
            } else {
                "0"
            }
        }

        //是否是营运车辆
        mYYGroup.setOnCheckedChangeListener { _, checkedId ->
            operating = if (checkedId == mYYTrue.id) "1" else "0"
        }

        radiogroup.setOnCheckedChangeListener { group, checkedId ->
            if (checkedId == CK_B1.id) {
                carSign = "2"
            } else if (checkedId == CK_B2.id) {
                carSign = "1"
            }
        }
//        //输入框监听
//        etPlateNumber.handlerText { s ->
//            val text = s.toString()
////            if (s.length == 8) {
////                rlPlateNumber1.setBackgroundResource(R.drawable.btn_round_blue)
////                imgIcon1.visibility = View.VISIBLE
////            } else {
////                rlPlateNumber1.setBackgroundResource(R.drawable.btn_round_green)
////                imgIcon1.visibility = View.GONE
////            }
//            if (text.contains("港") || text.contains("澳") || text.contains("学")) {
//                etPlateNumber.filters = arrayOf<InputFilter>(InputFilter.LengthFilter(7))
//            } else {
//                etPlateNumber.filters = arrayOf<InputFilter>(InputFilter.LengthFilter(8))
//            }
//        }
//        //车牌号输入框焦点监听
//        etPlateNumber.setOnFocusChangeListener { _, hasFocus ->
//            MyLog.d("软键盘获取焦点了")
//            if (hasFocus) {
//                confirm_button1.visibility = View.GONE
//                keyboardUtil!!.showKeyboard()
////                (getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).hideSoftInputFromWindow(this.currentFocus?.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
//            } else {
//                keyboardUtil!!.hideKeyboard()
//                confirm_button1.visibility = View.VISIBLE
//            }
//        }

    }
//
//    @SuppressLint("ClickableViewAccessibility")
//    override fun onTouch(v: View?, event: MotionEvent?): Boolean {
//        if (v!!.getId() == R.id.etPlateNumber) {
//            keyboardUtil!!.hideSystemKeyBroad()
//            keyboardUtil!!.hideSoftInputMethod()
//            if (!keyboardUtil!!.isShow) keyboardUtil!!.showKeyboard()
//            confirm_button1.visibility = View.INVISIBLE
//        } else {
//            if (keyboardUtil!!.isShow) keyboardUtil!!.hideKeyboard()
//            confirm_button1.visibility = View.VISIBLE
//        }
//        return false
//    }
//
//    override fun onTouchEvent(event: MotionEvent?): Boolean {
//        if (keyboardUtil!!.isShow) {
//            keyboardUtil!!.hideKeyboard()
//        }
//        return super.onTouchEvent(event)
//    }

    override fun onClick(v: View?) {
        if (v == confirm_button1) {
            //如果正在上传 禁止再次点击
            if (uploadingFlag) return
            if (TextUtils.isEmpty(remark.text.toString())) {
                Toast.makeText(applicationContext, "入场备注不能为空", Toast.LENGTH_SHORT).show()
            } else if (TextUtils.isEmpty(etPlateNumber.text.toString())) {
                Toast.makeText(applicationContext, "车牌号不能为空", Toast.LENGTH_SHORT).show()
            } else if (etPlateNumber.text.length < 7) {
                Toast.makeText(applicationContext, "车牌号格式不对", Toast.LENGTH_SHORT).show()
            } else if (TextUtils.isEmpty(carOwner.text.toString())) {
                Toast.makeText(applicationContext, "车主姓名不能为空", Toast.LENGTH_SHORT).show()
            } else if (TextUtils.isEmpty(ownerPhone.text.toString())) {
                Toast.makeText(applicationContext, "车主电话不能为空", Toast.LENGTH_SHORT).show()
            } else if (TextUtils.isEmpty(carVin.text.toString())) {
                Toast.makeText(applicationContext, "车架号不能为空", Toast.LENGTH_SHORT).show()
            } else if (ownerPhone.text.length < 11) {
                Toast.makeText(applicationContext, "电话号码长度不能低于11位", Toast.LENGTH_SHORT).show()
            } else if (files.isEmpty()) {
                Toast.makeText(applicationContext, "车辆照片最少2张", Toast.LENGTH_SHORT).show()
            }else if(mCarSelfCodeET.text.handlerNull().isEmpty()){
                showToast("请填写车辆自编码")
            }
            else {
                uploadingFlag=true
                progressDialog!!.setMessage("正在提交...")
                progressDialog!!.show()
                if (NetworkUtils.isConnected(applicationContext)) {
                    vehicleAdmissionViewModel!!.EntranceCar(
                        token!!,
                        filesToMultipartBodyParts(files)
                    )
                } else {
                    Toast.makeText(applicationContext, "请检查您的网络是否连接", Toast.LENGTH_SHORT).show()
                    progressDialog!!.dismiss()
                }
            }
        }
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == android.R.id.home) {
            finish()
        }
        return super.onOptionsItemSelected(item)
    }

    private fun tempFile(): String? {
        val filename: String = StringUtil.get32UUID().toString() + JPG
        return StorageUtil.getWritePath(filename, StorageType.TYPE_TEMP)
    }

    //上传
    fun filesToMultipartBodyParts(files: ArrayList<File>): ArrayList<MultipartBody.Part> {
        val parts: ArrayList<MultipartBody.Part> = ArrayList()
        for (i in files) {
            toRequestBodyOfImage("entrancePic", i)?.let { parts.add(it) }
        }
        toRequestBodyOfText("carId", carId!!)?.let { parts.add(it) }
        toRequestBodyOfText("drivingLicense", drivingLicense)?.let { parts.add(it) }
        toRequestBodyOfText("registration", registration)?.let { parts.add(it) }
        toRequestBodyOfText("idCardCopy", idCardCopy)?.let { parts.add(it) }
        toRequestBodyOfText("notice", notice)?.let { parts.add(it) }
        toRequestBodyOfText("attorneyPaper", attorneyPaper)?.let { parts.add(it) }
        toRequestBodyOfText("plateApplicationForm", plateApplicationForm)?.let { parts.add(it) }
        toRequestBodyOfText("carSign", carSign)?.let { parts.add(it) }
        toRequestBodyOfText("remark", remark.text.toString())?.let { parts.add(it) }
        toRequestBodyOfText("isOperatingCar", operating)?.let { parts.add(it) }

        //添加上传车主信息
        toRequestBodyOfText("ownerPhone", ownerPhone.text.toString())?.let { parts.add(it) }
        toRequestBodyOfText("ownerPlate", etPlateNumber.text.toString())?.let { parts.add(it) }
        toRequestBodyOfText("carOwner", carOwner.text.toString())?.let { parts.add(it) }
        toRequestBodyOfText("carVin", carVin.text.toString())?.let { parts.add(it) }
        //自编码
        toRequestBodyOfText("selfCode", mCarSelfCodeET.text.toString())?.let { parts.add(it) }
        return parts
    }

    private fun toRequestBodyOfText(
        keyStr: String,
        value: String
    ): MultipartBody.Part? {
        return MultipartBody.Part.createFormData(keyStr, value)
    }

    private fun toRequestBodyOfImage(keyStr: String, pFile: File): MultipartBody.Part? {
        val requestBody =
            RequestBody.create(MediaType.parse("multipart/form-data"), pFile)
        return MultipartBody.Part.createFormData(keyStr, pFile.name, requestBody)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE_PICKER && resultCode == Activity.RESULT_OK && data != null) {
            val list: List<ImageBean> =
                data.getParcelableArrayListExtra(ImagePicker.INTENT_RESULT_DATA)
            val resultList: MutableList<NineGridBean> =
                java.util.ArrayList()
            for (imageBean in list) {
                val nineGirdData = NineGridBean(imageBean.imagePath)
//                if (imageBean.imageId==null||imageBean.imageId=="null"||imageBean.imageId.isEmpty()){
//                    MyLog.d("我发现你是新照片")
//                    //将新拍照片存入相册
//                    MediaStore.Images.Media.insertImage(contentResolver,imageBean.imagePath,imageBean.imagePath,null);
//                }

                MyLog.d("我来康康1:${imageBean}")
                MyLog.d("我来康康2:${nineGirdData}")
                MyLog.d("我来康康3:${imageBean.imagePath}")
                val file = File(imageBean.imagePath)
                val newFile: File = CompressHelper.getDefault(this).compressToFile(file)
                files.add(newFile)
                resultList.add(nineGirdData)
            }
            ninegridview.addDataList(resultList)
        }
    }

    override fun onNineGirdItemDeleted(
        position: Int,
        gridBean: NineGridBean?,
        imageContainer: NineGirdImageContainer?
    ) {
        if (files.isEmpty()) {
            files.removeAt(position)
        }
    }

    override fun onNineGirdItemClick(
        position: Int,
        gridBean: NineGridBean?,
        imageContainer: NineGirdImageContainer?
    ) {

    }

    //照片选择器
    override fun onNineGirdAddMoreClick(cha: Int) {
        //编辑模式下，图片展示数量尚未达到最大数量时，会显示一个“+”号，点击后回调这里
        val imageLoader = ImagePicker()
            .cachePath(Environment.getExternalStorageDirectory().absolutePath)
//            .cachePath(galleryPath)

            .pickType(ImagePickType.MULTI)
            .displayer(ImagePickerLoader())
            .maxNum(cha)
            .start(this, REQUEST_CODE_PICKER)
    }

}